# -*- coding: utf-8 -*-
import logging

from common.utils.decorator import sql_wrapper
from common.utils.db import list_object, get, upsert, delete
from common.preset.model.preset import Lottery
from common.utils.tz import local_date_to_ts, now_ts

_LOGGER = logging.getLogger(__name__)


@sql_wrapper
def get_lottery(id):
    return get(Lottery, id)

@sql_wrapper
def get_activity_lottery(activity):
    lotterys = Lottery.query.filter(Lottery.type == activity).all()
    return lotterys

@sql_wrapper
def upsert_lottery(info, id=None):
    info['start_ts'] = local_date_to_ts(info['start_ts'])
    info['end_ts'] = local_date_to_ts(info['end_ts'])
    return upsert(Lottery, info, id)


@sql_wrapper
def list_lottery(query_dct):
    return list_object(query_dct, Lottery)


@sql_wrapper
def delete_lottery(id):
    delete(Lottery, id)


@sql_wrapper
def get_all_avaliable_lottery():
    now = now_ts()
    lotterys = Lottery.query.filter(Lottery.start_ts < now).filter(
        Lottery.end_ts > now).all()
    return lotterys
